package com.patrol.logisticsmanage.ui.equip;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.patrol.logisticsmanage.R;
import com.patrol.logisticsmanage.common.InputFilterMinMax;
import com.patrol.logisticsmanage.net.AppConfig;
import com.patrol.logisticsmanage.net.BaseObserver;
import com.patrol.logisticsmanage.net.BaseReponse;
import com.patrol.logisticsmanage.net.BaseRequest;
import com.patrol.logisticsmanage.ui.appear.model.SubCamp;
import com.patrol.logisticsmanage.ui.base.BaseFragment;
import com.patrol.logisticsmanage.ui.base.PickerDialog;
import com.patrol.logisticsmanage.ui.canteen.utils.ToastUtils;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.dialog.OnPickerChooseListener;
import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.OptionPicker;
import org.jaaksi.pickerview.util.Util;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class InfoFragment extends BaseFragment implements OptionPicker.OnOptionSelectListener {

    Unbinder unbinder;
    @BindView(R.id.et_height)
    EditText etHeight;
    @BindView(R.id.et_weight)
    EditText etWeight;
    @BindView(R.id.et_circumference1)
    EditText etCircumference1;
    @BindView(R.id.et_circumference2)
    EditText etCircumference2;
    @BindView(R.id.et_circumference3)
    EditText etCircumference3;
    @BindView(R.id.et_circumference4)
    EditText etCircumference4;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_idno)
    EditText etIdno;
    @BindView(R.id.sp_sex)
    Spinner spSex;

    StudentInfo studentInfo = new StudentInfo();
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.tv_card_type)
    TextView tvCardType;

    private OptionPicker mPicker;//证件类型
    DefaultCenterDecoration decoration;
    String cardType = "1";

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setContentView(R.layout.fragment_info);
        unbinder = ButterKnife.bind(this, getContentView());

        InputFilterMinMax.setRegin(etHeight,100,200);
        InputFilterMinMax.setRegin(etWeight,20,150);
        InputFilterMinMax.setRegin(etCircumference1,20,200);
        InputFilterMinMax.setRegin(etCircumference2,10,200);
        InputFilterMinMax.setRegin(etCircumference3,20,200);
        InputFilterMinMax.setRegin(etCircumference4,20,200);
//        initPickerView();
//        getCardType();
        getInfo();
    }


    private void initPickerView() {
        // 设置CenterDecoration
        decoration = new DefaultCenterDecoration(getContext());
        decoration
                .setLineColor(Color.parseColor("#dd199475"))
//                .setDrawable(Color.parseColor("#199475"))
                //.setDrawable(Color.parseColor("#999999"))
                .setLineWidth(1)
                .setMargin(Util.dip2px(getContext(), 10), Util.dip2px(getContext(), -3), Util.dip2px(getContext(), 10),
                        Util.dip2px(getContext(), -3));
        mPicker =
                new OptionPicker.Builder(getContext(), 1, this)
                        .dialog(new PickerDialog())
                        .setInterceptor(new BasePicker.Interceptor() {
                            @Override
                            public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                                int level = (int) pickerView.getTag();
                                pickerView.setVisibleItemCount(3);
                                // setInterceptor 可以根据level区分设置pickerview属性
                                pickerView.setCenterDecoration(decoration);
                                pickerView.setTextSize(15, 20);
                                pickerView.setColor(Color.parseColor("#199475"), Color.parseColor("#444444"));
                            }
                        }).create();
        PickerDialog pickerDialog = (PickerDialog) mPicker.dialog();
        Dialog dialog = pickerDialog.getDialog();

        pickerDialog.getTitleView().setText("请选择证件类型");
        // 设置弹窗
        dialog.setCanceledOnTouchOutside(true);
        dialog.getWindow().setGravity(Gravity.BOTTOM);

        // 拦截缺点按钮的事件
        pickerDialog.setOnPickerChooseListener(new OnPickerChooseListener() {
            @Override
            public boolean onConfirm() {
                cardType = cardTypes.get(mPicker.getSelectedPosition()[0]).getValue();
                tvCardType.setText(cardTypes.get(mPicker.getSelectedPosition()[0]).getTitle());
                dialog.dismiss();
                // 返回false表示拦截
                return false;
            }

            @Override
            public void onCancel() {
            }
        });

        mPicker.setData(cardTypes);
    }


    private void updateInfo(StudentInfo studentInfo) {
        BaseRequest.getInstance().getApiServise().addStudentInfo(studentInfo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(getContext()) {
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        ToastUtils.showToast("操作成功");
                        getInfo();
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {

                    }
                });
    }

    private void initView(StudentInfo info) {
        if (info==null||TextUtils.isEmpty(info.getId())){
            return;
        }else {
            etName.setEnabled(false);
            etIdno.setEnabled(false);
            spSex.setEnabled(false);
            tvCardType.setEnabled(false);
        }
        etName.setText(info.getName());
        etIdno.setText(info.getCardnu());
        etHeight.setText(info.getSheng());
        etWeight.setText(info.getTiz());
        etCircumference1.setText(info.getXiongw());
        etCircumference2.setText(info.getYaow());
        etCircumference3.setText(info.getTouw());
        etCircumference4.setText(info.getJiaoc());
        if (info.getSex().equals("1")) {
            spSex.setSelection(0);
        } else {
            spSex.setSelection(1);
        }
        for (int i = 0; i < cardTypes.size(); i++) {
            if (cardTypes.get(i).getValue().equals(info.getCardtype())) {
                tvCardType.setText(cardTypes.get(i).getTitle());
                cardType = cardTypes.get(i).getValue();
            }
        }
    }

    private void getInfo() {
        BaseRequest.getInstance().getApiServise().getStuInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<StudentInfo>(getContext()) {
                    @Override
                    public void onSuccess(BaseReponse<StudentInfo> baseReponse) {
                        studentInfo = baseReponse.getResults();
                        initView(studentInfo);
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {

                    }
                });
    }

    List<SubCamp> cardTypes = new ArrayList<>();

    private void getCardType() {
        BaseRequest.getInstance().getApiServise().getCardType()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<SubCamp>>(getContext()) {
                    @Override
                    public void onSuccess(BaseReponse<List<SubCamp>> baseReponse) {
                        List<SubCamp> types = baseReponse.getResults();
                        cardTypes.clear();
                        cardTypes.addAll(types);
                        mPicker.setData(cardTypes);
                        getInfo();
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {

                    }
                });
    }

    /**
     * 证件校验
     */
    private void getCardCheck(String cardNo) {
        BaseRequest.getInstance().getApiServise().checkCard("hq_bz_baseinfo", "cardnu", cardNo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(getContext()) {
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        //成功
                        updateInfo(studentInfo);
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                        ToastUtils.showToast(tBaseReponse.getMessage());
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {
                        ToastUtils.showToast("证件号码检验失败，请检查输入");
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.tv_update)
    public void onViewClicked() {
//        if (cardTypes.size() == 0) {
//            ToastUtils.showToast("获取证件类型失败，请稍后再试");
//            return;
//        }
//        if (TextUtils.isEmpty(etName.getText())) {
//            ToastUtils.showToast("姓名不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(etIdno.getText())) {
//            ToastUtils.showToast("证件号不能为空");
//            return;
//        }
        if (TextUtils.isEmpty(etHeight.getText())) {
            ToastUtils.showToast("身高不能为空");
            return;
        }
        if (TextUtils.isEmpty(etWeight.getText())) {
            ToastUtils.showToast("体重不能为空");
            return;
        }
        if (TextUtils.isEmpty(etCircumference1.getText())) {
            ToastUtils.showToast("胸围不能为空");
            return;
        }
        if (TextUtils.isEmpty(etCircumference2.getText())) {
            ToastUtils.showToast("腰围不能为空");
            return;
        }
        if (TextUtils.isEmpty(etCircumference3.getText())) {
            ToastUtils.showToast("臀围不能为空");
            return;
        }
        if (TextUtils.isEmpty(etCircumference4.getText())) {
            ToastUtils.showToast("脚长不能为空");
            return;
        }
        studentInfo = studentInfo
                .setUsername(AppConfig.getString("userName"))
                .setCardtype("1")
                .setCardnu(etIdno.getText().toString())
                .setName(etName.getText().toString())
                .setSex(spSex.getSelectedItemPosition() + 1 + "")
                .setSheng(Long.parseLong(etHeight.getText().toString()))
                .setTiz(Long.parseLong(etWeight.getText().toString()))
                .setXiongw(Long.parseLong(etCircumference1.getText().toString()))
                .setYaow(Long.parseLong(etCircumference2.getText().toString()))
                .setTouw(Long.parseLong(etCircumference3.getText().toString()))
                .setJiaoc(Long.parseLong(etCircumference4.getText().toString()));
//        if (TextUtils.isEmpty(studentInfo.getId())) {
//            getCardCheck(etIdno.getText().toString());
//        }else {
//            updateInfo(studentInfo);
//        }
        updateInfo(studentInfo);
    }

    @Override
    public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {

    }

    @OnClick(R.id.tv_card_type)
    public void onTypeClicked() {
        mPicker.show();
    }
}
